package com.dashu.base.utils;

import java.util.regex.Pattern;

/**
 * 正则表达式
 */
public class RegularUtils {

    /**
     * 校验IP是否合法
     *
     * @param ipstr
     * @return
     */
    public static boolean isIpv4(String... ipstr) {
        String regIp = "^([1-9]|[1-9]\\d|1\\d{2}|2[0-1]\\d|22[0-3])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}$";

        for (String ip : ipstr) {
            boolean flag = ip.matches(regIp);
            if (!flag) {
                return false;
            }
        }
        return true;
    }


    /**
     * 判断url是否合法
     *
     * @param url
     * @return
     */
    public static boolean isUrl(String url) {
        String regex = "^([hH][tT]{2}[pP]:/*|[hH][tT]{2}[pP][sS]:/*|[fF][tT][pP]:/*)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\/])+(\\?{0,1}(([A-Za-z0-9-~]+\\={0,1})([A-Za-z0-9-~]*)\\&{0,1})*)$";
        Pattern pattern = Pattern.compile(regex);
        return pattern.matcher(url).matches();
    }


    //方法1、通过String的indexOf(String str, int fromIndex)方法
    public static boolean matchStringByIndexOf(String parent, String child) {
        int count = 0;
        int index = 0;
        while ((index = parent.indexOf(child, index)) != -1) {
            index = index + child.length();
            count++;
        }
//        System.out.println( "匹配个数为"+count );                              //结果输出
        if (count > 0) return true;
        return false;
    }
}
